﻿var map = null;
var overlays = [];
var overlaysPolys = [];
var scuts = [];
var ports = [];
var latsPoli = [];
var longsPoli = [];
var course = [];

function MainLoadMapV3(startLat, startLng, course, zoom, country, options) {
    if (typeof (options) == 'undefined')
        options = {}; // {startLat: startLat, startLng: startLng, startMap: G_SATELLITE_MAP, course: course, zoom: zoom, country: country};

    if (typeof (options.startMap) == 'undefined') options.startMap = google.maps.MapTypeId.ROADMAP;
    if (typeof (options.markerTitle) == 'undefined') options.markerTitle = "";
    if (typeof (options.createMarker) == 'undefined') options.createMarker = true;
    if (typeof (options.altCenter) == 'undefined') options.altCenter = null;


    if (document.getElementById("map_canvas")) {
        var myOptions = {
            zoom: 7,
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.LARGE
            },
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        

        // ====== Restricting the range of Zoom Levels =====
        // Get the list of map types      
//        var mt = map.getMapTypes();
//        for (var i = 0; i < mt.length; i++) {
//            //mt[i].getMinimumResolution = function() {return 7;}
//            mt[i].getMaximumResolution = function() { return 18; }
//        }

        if (startLat == null || startLng == null || zoom == null) {
            map.setCenter(new google.maps.LatLng(39.56300, -6.8000));
            map.setZoom(6);
        }
        else {
            var latLngCenter = new google.maps.LatLng(startLat, startLng);
            var marquerOptions = {};
            if (options.altCenter != null) {
                latLngCenter = options.altCenter;
                marquerOptions.center = false;
            }

            map.setCenter(latLngCenter);
            map.setZoom(zoom);
            
            
            if (options.createMarker)
                createMarquer(startLat, startLng, course, options.markerTitle, marquerOptions);
        }
    }
    
       
}

function createMarquer(lat, lng, course, desc, options) {
    var point = new google.maps.LatLng(lat, lng);
    var car = new google.maps.MarkerImage();
    car.url = "../Imagens/Cars/caricon-" + Math.floor(course / 45) + ".png";
    car.size = new google.maps.Size(32, 32);
    car.anchor = new google.maps.Point(16, 16);
    var shadow = new google.maps.MarkerImage('../Imagens/caricon_shadow.png', new google.maps.Size(42, 18), new google.maps.Point(0, 0), new google.maps.Point(16, 16));
    var marker = new google.maps.Marker({
        position: point,
        icon: car,
        shadow: shadow,
        clickable: true,
        title: desc,
        map: map
    });
}

function showLine(overlays, overlaysPolys) {
    for (i = 0; i < overlays.length; i++) {
        overlays[i].setMap(map);
        //        var marker = new google.maps.Marker({
        //            position: new google.maps.LatLng(overlays[i].getPosition().lat(), overlays[i].getPosition().lng()),
        //            icon: overlays[i].getIcon(),
        //            clickable: false,
        //            map: map
        //        });
    }

    for (i = 0; i < overlaysPolys.length; i++) {
        overlaysPolys[i].setMap(map);
    }
}

function verificaScuts(scuts, latsPoli, longsPoli, course) {
    google.maps.Polygon.prototype.Contains = function(point) {
        // ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
        var crossings = 0,
                path = this.getPath();
        // for each edge
        for (var i = 0; i < path.getLength(); i++) {
            var a = path.getAt(i),
                    j = i + 1;
            if (j >= path.getLength()) {
                j = 0;
            }
            var b = path.getAt(j);
            if (rayCrossesSegment(point, a, b)) {
                crossings++;
            }
        }
        // odd number of crossings?
        return (crossings % 2 == 1);
        function rayCrossesSegment(point, a, b) {
            var px = point.lng(),
                    py = point.lat(),
                    ax = a.lng(),
                    ay = a.lat(),
                    bx = b.lng(),
                    by = b.lat();
            if (ay > by) {
                ax = b.lng();
                ay = b.lat();
                bx = a.lng();
                by = a.lat();
            }
            if (py == ay || py == by) py += 0.00000001;
            if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
            if (px < Math.min(ax, bx)) return true;
            var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity;
            var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity;
            return (blue >= red);
        }
    };

    var getCourse = function(val) {
        if (val < 25.0) return "Norte";
        if (val >= 25.0 && val < 90.0) return "Nordeste";
        if (val >= 90.0 && val < 135.0) return "Este";
        if (val >= 135.0 && val < 180.0) return "Sudeste";
        if (val >= 180.0 && val < 205.0) return "Sul";
        if (val >= 205.0 && val < 270.0) return "Sudoeste";
        if (val >= 270.0 && val < 315.0) return "Oeste";
        if (val >= 315.0 && val < 360.0) return "Noroeste";
    };
    
    
    var polygonoo = [];
    for (var l = 1; l < longsPoli.length; l++) {

        var Latitude_Ant_Norte = eval(latsPoli[l - 1]) + 0.00025;
        var Latitude_Ant_Sul = eval(latsPoli[l - 1]) - 0.00025;
        //alert("---->" + arrayLatitudesAnt[u] + "---->" + Latitude_Ant_Norte + "---->" + Latitude_Ant_Sul);
        var Latitude_Prox_Norte = eval(latsPoli[l]) + 0.00025;
        var Latitude_Prox_Sul = eval(latsPoli[l]) - 0.00025;
        //---------------------------Fim Calculo Poligono para trajectos diferentes de Norte e Sul-------------------------

        var Longitude_Ant_Oeste = eval(longsPoli[l-1]) + 0.00025;
        var Longitude_Ant_Este = eval(longsPoli[l - 1]) - 0.00025;

        var Longitude_Prox_Oeste = eval(longsPoli[l]) + 0.00025;
        var Longitude_Prox_Este = eval(longsPoli[l]) - 0.00025;
        var coordenadasPontos = [];
        if (getCourse(course[l]) == "Norte" || getCourse(course[l]) == "Sul") {
            coordenadasPontos = [
                    new google.maps.LatLng(latsPoli[l-1], Longitude_Ant_Oeste),
                    new google.maps.LatLng(latsPoli[l-1], Longitude_Ant_Este),
                    new google.maps.LatLng(latsPoli[l], Longitude_Prox_Este),
                    new google.maps.LatLng(latsPoli[l], Longitude_Prox_Oeste)
                    ];
        }
        else {
            coordenadasPontos = [
                    new google.maps.LatLng(Latitude_Ant_Norte, longsPoli[l-1]),
                    new google.maps.LatLng(Latitude_Ant_Sul, longsPoli[l-1]),
                    new google.maps.LatLng(Latitude_Prox_Sul, longsPoli[l]),
                    new google.maps.LatLng(Latitude_Prox_Norte, longsPoli[l])
                    ];
        }
        
        polygonoo[l] = new google.maps.Polygon({ paths: coordenadasPontos, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35});
        
            

        for (i = 0; i < scuts.length; i++) {
            if (polygonoo[l].Contains(scuts[i].getPosition())) {
//                alert(scuts[i].getPosition());
                scuts[i].setMap(map);  
                              
            }
        }
    }
    
}

